/**
 * 后台服务脚本 - 图片视频下载器
 * 负责处理下载管理、右键菜单、数据存储等核心功能
 */

// 全局变量
let downloadManager;
let storageManager;
let contextMenuManager;

/**
 * 下载管理器类
 */
class DownloadManager {
    constructor() {
        this.downloadQueue = new Map();
        this.activeDownloads = new Set();
        this.maxConcurrent = 3;
        this.settings = {};
    }

    /**
     * 初始化下载管理器
     */
    async init(settings = {}) {
        this.settings = {
            maxConcurrent: 3,
            maxFileSize: 100 * 1024 * 1024, // 100MB
            downloadPath: 'downloads',
            filenamePattern: '{filename}',
            ...settings
        };

        this.maxConcurrent = this.settings.maxConcurrent;
        console.log('下载管理器初始化完成');
    }

    /**
     * 下载文件
     */
    async downloadFiles(files, settings = {}) {
        const downloadSettings = { ...this.settings, ...settings };
        const results = [];

        console.log(`开始下载 ${files.length} 个文件...`);

        for (const file of files) {
            try {
                // 生成文件名
                const filename = this.generateFilename(file, downloadSettings);

                // 添加到下载队列
                const downloadItem = {
                    id: file.id,
                    url: file.url,
                    filename: filename,
                    type: file.type,
                    size: file.size || 0,
                    state: 'pending',
                    progress: 0,
                    startTime: Date.now(),
                    settings: downloadSettings
                };

                this.downloadQueue.set(file.id, downloadItem);
                results.push({
                    id: file.id,
                    success: true,
                    downloadItem: downloadItem
                });

                // 开始下载
                this.processDownloadQueue();

            } catch (error) {
                console.error(`下载文件失败: ${file.url}`, error);
                results.push({
                    id: file.id,
                    success: false,
                    error: error.message
                });
            }
        }

        return results;
    }

    /**
     * 生成文件名
     */
    generateFilename(file, settings) {
        let filename = file.filename || this.getFilenameFromUrl(file.url);

        // 清理文件名
        filename = this.sanitizeFilename(filename);

        // 应用命名模式
        const pattern = settings.filenamePattern || '{filename}';
        filename = pattern.replace('{filename}', filename);

        return filename;
    }

    /**
     * 清理文件名
     */
    sanitizeFilename(filename) {
        return filename.replace(/[<>:"/\\|?*]/g, '_');
    }

    /**
     * 从URL获取文件名
     */
    getFilenameFromUrl(url) {
        try {
            const urlObj = new URL(url);
            const pathname = urlObj.pathname;
            const filename = pathname.split('/').pop();
            return filename || 'unknown';
        } catch (error) {
            return 'unknown';
        }
    }

    /**
     * 处理下载队列
     */
    async processDownloadQueue() {
        if (this.activeDownloads.size >= this.maxConcurrent) {
            return;
        }

        for (const [id, item] of this.downloadQueue) {
            if (item.state === 'pending' && this.activeDownloads.size < this.maxConcurrent) {
                this.startDownload(item);
            }
        }
    }

    /**
     * 开始下载
     */
    async startDownload(item) {
        try {
            item.state = 'in_progress';
            this.activeDownloads.add(item.id);

            const downloadId = await chrome.downloads.download({
                url: item.url,
                filename: item.filename,
                saveAs: false
            });

            item.downloadId = downloadId;
            console.log(`开始下载: ${item.filename}`);

        } catch (error) {
            console.error(`下载失败: ${item.filename}`, error);
            item.state = 'error';
            item.error = error.message;
            this.activeDownloads.delete(item.id);
        }
    }

    /**
     * 更新下载状态
     */
    updateDownloadStatus(downloadId, state) {
        for (const [id, item] of this.downloadQueue) {
            if (item.downloadId === downloadId) {
                item.state = state;
                if (state === 'complete' || state === 'interrupted') {
                    this.activeDownloads.delete(id);
                    this.processDownloadQueue();
                }
                break;
            }
        }
    }

    /**
     * 暂停下载
     */
    async pauseDownload(downloadId) {
        try {
            await chrome.downloads.pause(downloadId);
            console.log(`下载已暂停: ${downloadId}`);
        } catch (error) {
            console.error('暂停下载失败:', error);
            throw error;
        }
    }

    /**
     * 恢复下载
     */
    async resumeDownload(downloadId) {
        try {
            await chrome.downloads.resume(downloadId);
            console.log(`下载已恢复: ${downloadId}`);
        } catch (error) {
            console.error('恢复下载失败:', error);
            throw error;
        }
    }

    /**
     * 取消下载
     */
    async cancelDownload(downloadId) {
        try {
            await chrome.downloads.cancel(downloadId);
            console.log(`下载已取消: ${downloadId}`);
        } catch (error) {
            console.error('取消下载失败:', error);
            throw error;
        }
    }
}

/**
 * 存储管理器类
 */
class StorageManager {
    constructor() {
        this.defaultSettings = {
            downloadPath: 'downloads',
            filenamePattern: '{filename}',
            maxConcurrent: 3,
            maxFileSize: 100 * 1024 * 1024,
            autoDownload: false,
            showNotifications: true
        };
    }

    /**
     * 获取设置
     */
    async getSettings() {
        try {
            const result = await chrome.storage.sync.get('settings');
            return result.settings || this.defaultSettings;
        } catch (error) {
            console.error('获取设置失败:', error);
            return this.defaultSettings;
        }
    }

    /**
     * 更新设置
     */
    async updateSettings(settings) {
        try {
            await chrome.storage.sync.set({ settings });
            console.log('设置已更新');
        } catch (error) {
            console.error('更新设置失败:', error);
            throw error;
        }
    }

    /**
     * 获取下载历史
     */
    async getDownloadHistory() {
        try {
            const result = await chrome.storage.local.get('downloadHistory');
            return result.downloadHistory || [];
        } catch (error) {
            console.error('获取下载历史失败:', error);
            return [];
        }
    }

    /**
     * 添加下载历史
     */
    async addDownloadHistory(downloadItem) {
        try {
            const history = await this.getDownloadHistory();
            history.unshift({
                ...downloadItem,
                timestamp: Date.now()
            });

            // 只保留最近100条记录
            if (history.length > 100) {
                history.splice(100);
            }

            await chrome.storage.local.set({ downloadHistory: history });
        } catch (error) {
            console.error('添加下载历史失败:', error);
        }
    }
}

/**
 * 右键菜单管理器类
 */
class ContextMenuManager {
    constructor() {
        this.menus = new Map();
    }

    /**
     * 创建右键菜单
     */
    async createMenus() {
        try {
            await chrome.contextMenus.removeAll();

            // 图片右键菜单
            chrome.contextMenus.create({
                id: 'downloadImage',
                title: '下载图片',
                contexts: ['image']
            });

            // 视频右键菜单
            chrome.contextMenus.create({
                id: 'downloadVideo',
                title: '下载视频',
                contexts: ['video']
            });

            // 页面右键菜单
            chrome.contextMenus.create({
                id: 'downloadAllImages',
                title: '下载所有图片',
                contexts: ['page']
            });

            chrome.contextMenus.create({
                id: 'downloadAllVideos',
                title: '下载所有视频',
                contexts: ['page']
            });

            console.log('右键菜单创建完成');
        } catch (error) {
            console.error('创建右键菜单失败:', error);
        }
    }
}

/**
 * 初始化后台服务
 */
async function initializeBackground() {
    console.log('初始化后台服务...');

    // 初始化各个管理器
    downloadManager = new DownloadManager();
    storageManager = new StorageManager();
    contextMenuManager = new ContextMenuManager();

    // 初始化下载管理器
    const settings = await storageManager.getSettings();
    await downloadManager.init(settings);

    // 设置右键菜单
    await contextMenuManager.createMenus();

    // 监听来自内容脚本和弹出窗口的消息
    setupMessageListeners();

    // 监听下载事件
    setupDownloadListeners();

    console.log('后台服务初始化完成');
}

/**
 * 设置消息监听器
 */
function setupMessageListeners() {
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
        console.log('收到消息:', request);

        switch (request.action) {
            case 'scanMedia':
                handleScanMedia(request, sender, sendResponse);
                break;
            case 'downloadFiles':
                handleDownloadFiles(request, sendResponse);
                break;
            case 'getDownloadHistory':
                handleGetDownloadHistory(sendResponse);
                break;
            case 'getSettings':
                handleGetSettings(sendResponse);
                break;
            case 'updateSettings':
                handleUpdateSettings(request, sendResponse);
                break;
            case 'pauseDownload':
                handlePauseDownload(request, sendResponse);
                break;
            case 'resumeDownload':
                handleResumeDownload(request, sendResponse);
                break;
            case 'cancelDownload':
                handleCancelDownload(request, sendResponse);
                break;
            default:
                sendResponse({ success: false, error: '未知操作' });
        }

        // 返回true表示异步响应
        return true;
    });
}

/**
 * 处理媒体扫描请求
 */
async function handleScanMedia(request, sender, sendResponse) {
    try {
        // 获取当前活动标签页
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        if (!tab) {
            throw new Error('无法获取当前标签页');
        }

        // 检查标签页URL是否支持脚本注入
        if (!tab.url || tab.url.startsWith('chrome://') || tab.url.startsWith('chrome-extension://') || tab.url.startsWith('edge://')) {
            throw new Error('无法在此页面执行扫描');
        }

        // 尝试注入并执行脚本
        let result;
        try {
            result = await chrome.scripting.executeScript({
                target: { tabId: tab.id },
                function: scanPageMedia
            });
        } catch (scriptError) {
            console.warn('脚本注入失败，尝试使用content script:', scriptError);

            // 回退方案：通过content script获取媒体数据
            try {
                const response = await chrome.tabs.sendMessage(tab.id, {
                    action: 'getMediaData'
                });

                if (!response || !response.success) {
                    throw new Error(response?.error || '无法获取页面媒体数据');
                }

                // 构造返回格式
                result = [{ result: response.data }];
            } catch (messageError) {
                console.error('Content script消息失败:', messageError);
                throw new Error('无法与页面通信，请刷新页面后重试');
            }
        }

        if (!result || !result[0] || !result[0].result) {
            throw new Error('执行脚本失败');
        }

        const mediaData = result[0].result;
        console.log('扫描结果:', mediaData);
        sendResponse({ success: true, data: mediaData });
    } catch (error) {
        console.error('扫描媒体失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 页面媒体扫描函数（在内容脚本中执行）
 */
function scanPageMedia() {
    // 内联getFilenameFromUrl函数
    function getFilenameFromUrl(url) {
        try {
            const urlObj = new URL(url);
            const pathname = urlObj.pathname;
            const filename = pathname.split('/').pop();
            return filename || 'unknown';
        } catch (error) {
            return 'unknown';
        }
    }

    const mediaData = {
        images: [],
        videos: [],
        timestamp: Date.now()
    };

    // 扫描图片
    const images = document.querySelectorAll('img');
    images.forEach((img, index) => {
        if (img.src && img.src.startsWith('http')) {
            mediaData.images.push({
                id: `img_${index}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                url: img.src,
                alt: img.alt || '',
                width: img.naturalWidth || img.width,
                height: img.naturalHeight || img.height,
                title: img.title || '',
                filename: getFilenameFromUrl(img.src)
            });
        }
    });

    // 扫描视频
    const videos = document.querySelectorAll('video, iframe[src*="video"], iframe[src*="youtube"], iframe[src*="vimeo"]');
    videos.forEach((video, index) => {
        if (video.src || video.querySelector('source')) {
            const videoUrl = video.src || video.querySelector('source').src;
            if (videoUrl && videoUrl.startsWith('http')) {
                mediaData.videos.push({
                    id: `video_${index}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
                    url: videoUrl,
                    title: video.title || '',
                    width: video.videoWidth || video.width,
                    height: video.videoHeight || video.height,
                    duration: video.duration || 0,
                    filename: getFilenameFromUrl(videoUrl)
                });
            }
        }
    });

    return mediaData;
}

/**
 * 处理文件下载请求
 */
async function handleDownloadFiles(request, sendResponse) {
    try {
        const { files, settings } = request;
        const downloadResults = await downloadManager.downloadFiles(files, settings);
        sendResponse({ success: true, data: downloadResults });
    } catch (error) {
        console.error('下载文件失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理获取下载历史请求
 */
async function handleGetDownloadHistory(sendResponse) {
    try {
        const history = await storageManager.getDownloadHistory();
        sendResponse({ success: true, data: history });
    } catch (error) {
        console.error('获取下载历史失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理获取设置请求
 */
async function handleGetSettings(sendResponse) {
    try {
        const settings = await storageManager.getSettings();
        sendResponse({ success: true, data: settings });
    } catch (error) {
        console.error('获取设置失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理更新设置请求
 */
async function handleUpdateSettings(request, sendResponse) {
    try {
        const { settings } = request;
        await storageManager.updateSettings(settings);
        sendResponse({ success: true });
    } catch (error) {
        console.error('更新设置失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理暂停下载请求
 */
async function handlePauseDownload(request, sendResponse) {
    try {
        const { downloadId } = request;
        await downloadManager.pauseDownload(downloadId);
        sendResponse({ success: true });
    } catch (error) {
        console.error('暂停下载失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理恢复下载请求
 */
async function handleResumeDownload(request, sendResponse) {
    try {
        const { downloadId } = request;
        await downloadManager.resumeDownload(downloadId);
        sendResponse({ success: true });
    } catch (error) {
        console.error('恢复下载失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 处理取消下载请求
 */
async function handleCancelDownload(request, sendResponse) {
    try {
        const { downloadId } = request;
        await downloadManager.cancelDownload(downloadId);
        sendResponse({ success: true });
    } catch (error) {
        console.error('取消下载失败:', error);
        sendResponse({ success: false, error: error.message });
    }
}

/**
 * 设置下载事件监听器
 */
function setupDownloadListeners() {
    chrome.downloads.onChanged.addListener((downloadDelta) => {
        console.log('下载状态变化:', downloadDelta);

        // 更新下载状态
        if (downloadDelta.state) {
            downloadManager.updateDownloadStatus(downloadDelta.id, downloadDelta.state.current);
        }

        // 发送状态更新到弹出窗口
        chrome.runtime.sendMessage({
            action: 'downloadStatusChanged',
            data: downloadDelta
        }).catch(() => {
            // 弹出窗口可能未打开，忽略错误
        });
    });

    chrome.downloads.onCreated.addListener((downloadItem) => {
        console.log('新下载任务:', downloadItem);

        // 记录下载历史
        storageManager.addDownloadHistory(downloadItem);
    });
}

/**
 * 右键菜单点击处理
 */
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
    console.log('右键菜单点击:', info);

    try {
        switch (info.menuItemId) {
            case 'downloadImage':
                await handleContextMenuDownload(info, tab, 'image');
                break;
            case 'downloadVideo':
                await handleContextMenuDownload(info, tab, 'video');
                break;
            case 'downloadAllImages':
                await handleContextMenuDownloadAll(tab, 'images');
                break;
            case 'downloadAllVideos':
                await handleContextMenuDownloadAll(tab, 'videos');
                break;
        }
    } catch (error) {
        console.error('右键菜单处理失败:', error);
    }
});

/**
 * 处理右键菜单单个下载
 */
async function handleContextMenuDownload(info, tab, type) {
    const fileData = {
        id: `context_${Date.now()}`,
        url: info.srcUrl,
        filename: getFilenameFromUrl(info.srcUrl),
        type: type,
        title: info.title || '',
        alt: info.alt || ''
    };

    const settings = await storageManager.getSettings();
    await downloadManager.downloadFiles([fileData], settings);
}

/**
 * 处理右键菜单批量下载
 */
async function handleContextMenuDownloadAll(tab, type) {
    const result = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        function: scanPageMedia
    });

    const mediaData = result[0].result;
    const files = type === 'images' ? mediaData.images : mediaData.videos;

    if (files.length > 0) {
        const settings = await storageManager.getSettings();
        await downloadManager.downloadFiles(files, settings);
    }
}

// 扩展安装时初始化
chrome.runtime.onInstalled.addListener(() => {
    console.log('扩展已安装，开始初始化...');
    initializeBackground();
});

// 扩展启动时初始化
initializeBackground(); 